from clang.cindex import Cursor, CursorKind
from typing import Generator, Tuple
from ..code_attributes import (
    beautified_print_ast,
    extract_literal_value,
    split_binary_operator,
    split_compound_assignment,
)
from MelodieFuncFlow import MelodieGenerator

# def get_variable

def get_variable_write(cursor: Cursor) -> MelodieGenerator[Tuple[Cursor, str, Cursor]]:
    """
    Get the variable write operations from a function
    """
    def _(cu: Cursor):
        for child in cu.walk_preorder():
            match child:
                case Cursor(kind=CursorKind.VAR_DECL):
                    var = child.spelling
                    value = next(child.get_children())
                    yield var, "=", value
                    # print(var, extract_literal_value(value) or value.spelling)
                case Cursor(kind=CursorKind.BINARY_OPERATOR):
                    left, op, right = split_binary_operator(child)
                    # print(op)
                    match op:
                        case "=":
                            yield left, op, right
                        case _:
                            pass
                case Cursor(kind=CursorKind.COMPOUND_ASSIGNMENT_OPERATOR):
                    lvalue, op, rvalue = split_compound_assignment(child)
                    match op:
                        case "+=" | "-=" | "*=" | "/=" | "<<=" | ">>=" | "&=" | "|=" | "^=":
                            yield lvalue, op, rvalue
                        case _:
                            pass
    return MelodieGenerator(_(cursor))